<?php
/**
 * Created by PhpStorm.
 * User: 姚荣
 * Date: 2017/5/27
 * Time: 17:57
 */
//----------------------------------
// 管理员
//----------------------------------

namespace app\home\controller;

use app\common\controller\Base;
use app\common\model\Role;
use app\common\model\Admin as nAdmin;
use think\Validate;

class Admin extends Base
{
    protected $role;
    protected $admin;

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->role = new Role();
        $this->admin = new nAdmin();
    }

	public function index(){
		$this->veryauth();//验证权限
		return $this->fetch();
	}

	//获取管理员列表，分页搜索
	public function adminlist(){
		$this->veryauth(1);//验证权限
		
		$pagenum = intval(input('get.pageNumber'));
		$pageSize = intval(input('get.pageSize'));
		$sortName = input('get.sortName');
		$sortOrder = input('get.sortOrder');
		
		$search = input('get.searchText');
		$where=[];
		if(!empty($search)){
		$where['name'] = $search;
		}
		
		if($pagenum==''||$pagenum<=0){
			$pagenum=1;
		}

		$retArray = [];
		
		$sortwhere = $sortName.' '.$sortOrder;


		$sortwhere = $sortName == '' ?  ' id asc ' : $sortwhere;

		$adminTotal = $this->admin->where($where)->count();

		$adminInfo = $this->admin->order($sortwhere)->where($where)->page($pagenum,$pageSize)->select();
		
		//dump($this->admin->getLastSql());
		
		$retArray['total'] = intval($adminTotal);
		$retArray['rows'] = $adminInfo;
		
		return json($retArray);
	}



	//角色列表
	public function rolelist(){
		$id = input('post.id');
		
		$rolelist = $this->role->order('id asc')->select();
        $rolearray = '';
		if($id==-1){
			foreach($rolelist as $key=>$v){
			if($key==0){
				$rolearray .= "<label><input type='radio' checked value='".$v['id']."' name='role'/>".$v['rolename']."</label>";
			}else{
				$rolearray .= "<label><input type='radio' value='".$v['id']."' name='role'/>".$v['rolename']."</label>";
			}

			}
		}else{
			if($id==0){
					$rolearray .= "<label><input type='radio' checked value='0' name='role'/>超级管理员</label>";
				}else{
					foreach($rolelist as $key=>$v){

							if($v['id']==$id){
								$rolearray .= "<label><input type='radio' checked value='".$v['id']."' name='role'/>".$v['rolename']."</label>";
							}else{
								$rolearray .= "<label><input type='radio' value='".$v['id']."' name='role'/>".$v['rolename']."</label>";
							}
					}
				}
		}

		return json($rolearray);

	}


	//删除选中会员
	/*
	 * $id 多个用户id拼装的字符,用‘,’分割，如："2,1,4,5,6"
	 * */
	public function deladmin(){
		$this->veryauth(1);//验证权限
		
		$mid = input('post.id');
		if(empty($mid)){
			$retArray = ['rel'=>0,'msg'=>'参数不能为空'];
			return json($retArray);
		}
		
		$midarray = explode(',', $mid);
		$key = in_array('1', $midarray);
		
		if($key){
			unset($midarray[array_search('1',$midarray)]);
		}
		
		if(count($midarray)>0){
		$mid = implode(',', $midarray);
		
		$where['id'] = ['in',$mid];

		$delmem = $this->admin->where($where)->delete();
		
		if($delmem){
			$retArray = ['rel'=>1,'msg'=>'删除成功'];
		}else{
			$retArray = ['rel'=>0,'msg'=>'删除失败'];
		}
		}else{
			$retArray = ['rel'=>0,'msg'=>'超级管理员禁止删除'];
		}
		
		return json($retArray);
	}



	//ajax增加会员
	public function addadmin(){
		$this->veryauth(1);//验证权限
        $adminarray = input('post.');

        // 数据验证
        $validate = new Validate([
                'name' => 'require',
                'mobile' => ['require','regex'=>'/^(0|86|17951)?(13[0-9]|15[012356789]|17[0-9]|18[0-9]|14[57])[0-9]{8}$/'],
                'pwd' => 'require'
            ],
            $msg = [
                'name' => '姓名必须填写',
                'mobile.require' => '手机号码必须填写',
                'mobile.regex' => '手机号码格式不正确',
                'pwd' => '密码必须填写'
            ]);

        if (!$validate->check($adminarray)) {
            $ajaxresult = ['rel' => 0, 'msg' => $validate->getError()];
            return json($ajaxresult);
        }

		$now = time();

			$adminarray['addtime'] = $now;
			$adminarray['logintime'] = $now;
			$adminarray['pwd'] = md5($adminarray['pwd']);

			$mwhere = ['name'=>$adminarray['name']];
			$adminif = $this->admin->where($mwhere)->find();
			if($adminif){
				$ajaxresult = ['rel'=>0,'msg'=>'管理员已存在'];
				return json($ajaxresult);
			}

			$rolename = $this->role->find($adminarray['roleid']);
			$adminarray['rolename'] = $rolename['rolename'];
				$upinfo = $this->admin->allowField(true)->isUpdate(false)->save($adminarray);
				if($upinfo){
					$ajaxresult = ['rel'=>1,'msg'=>'添加成功'];
				}else{
					$ajaxresult = ['rel'=>0,'msg'=>'添加失败'];
				}

		return json($ajaxresult);
	}

	//ajax修改管理员
	public function editeradmin(){
		$this->veryauth(1);//验证权限
        $adminarray = input('post.');

        // 数据验证
        $validate = new Validate([
                'id' => 'number',
                'name' => 'require'
            ]
            ,
            $msg = [
                'id' => 'id不正确',
                'name' => '姓名必须填写'
            ]);

        if (!$validate->check($adminarray)) {
            $ajaxresult = ['rel' => 0, 'msg' => $validate->getError()];
            return json($ajaxresult);
        }

			$repass = input('post.repass');
			if($adminarray['pwd']!=$repass){
				$ajaxresult = ['rel'=>0,'msg'=>'确认密码错误'];
				return json($ajaxresult);
			}
			$mwhere = ['name'=>$adminarray['name']];
			$mwhere['id'] = ['neq',$adminarray['id']];
			$adminif = $this->admin->where($mwhere)->find();
			if($adminif){
				$ajaxresult = ['rel'=>0,'msg'=>'管理员已存在'];
				return json($ajaxresult);
			}
			$where = ['id'=>$adminarray['id']];
			$verimem = $this->admin->find($where);
			if(empty($adminarray['pwd'])){
				unset($adminarray['pwd']);
			}else{
				$adminarray['pwd'] = md5($adminarray['pwd']);
			}

			$rolename = $this->role->find($adminarray['roleid']);
			if(!empty($rolename)){
				$adminarray['rolename'] = $rolename['rolename'];
			}else{
				$adminarray['rolename'] = '超级管理员';
			}

				if($verimem){
					$upinfo = $this->admin->allowField(true)->isUpdate(true)->save($adminarray);
					if($upinfo){
						$ajaxresult = ['rel'=>1,'msg'=>'修改成功'];
					}else{
						$ajaxresult = ['rel'=>0,'msg'=>'修改失败或信息没有改变'];
					}
				}else{
					$ajaxresult = ['rel'=>0,'msg'=>'管理员不存在'];
				}


		return json($ajaxresult);
	}

    //ajax修改管理员密码
    public function resivepwdajax(){
        $this->veryauth(1);//验证权限

        $id = session('aid');
        $oldpwd = input('post.pwd');
        $newpwd = input('post.newpwd');
        $confirmpwd = input('post.confirmpwd');

        if(empty($oldpwd)){
            $ajaxresult = ['rel'=>0,'msg'=>'密码错误'];
            return json($ajaxresult);
        }
        if($newpwd!=$confirmpwd){
            $ajaxresult = ['rel'=>0,'msg'=>'两次密码不一致'];
            return json($ajaxresult);
        }

        $where = ['id'=>$id];
        $verimem = $this->admin->where($where)->find();

        if($verimem['pwd'] != md5($oldpwd)){
            $ajaxresult = ['rel'=>0,'msg'=>'密码错误'];
            return json($ajaxresult);
        }else{
            $data = ['id'=>$id,'pwd'=>md5($newpwd)];
        }
        //$id = array('id'=>$id);
        if($this->admin->allowField(true)->isUpdate(true)->save($data)){
            session(null);
            cookie(null);
            $ajaxresult = ['rel'=>1,'msg'=>'修改成功'];
        }else{
            $ajaxresult = ['rel'=>0,'msg'=>'信息没有改变'];
        }

        return json($ajaxresult);

    }



}
